<template>
  <div class="commodity" v-if="details">
    <i class="iconfont icon-left gobackIcon" @click="goUpperStory()" style="z-index:2"></i>
    <div class="topImg" style="height:270px;">
      <van-swipe :autoplay="0" indicator-color="white">
        <van-swipe-item v-for="(item,i) in condensation.image" :key="i">
          <img :src="item" alt />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="info">
      <van-card>
        <div class="titleInfo" slot="price">
          <span class="name">零售价</span>
          <span class="value">￥{{details.retailPrice}}</span>
        </div>
        <div class="text" slot="bottom">
          <p>{{details.productName}}</p>
          <span>
            <i class="iconfont icon-collect" @click="addFavorites()"></i>收藏
          </span>
        </div>
      </van-card>
    </div>
    <div class="contentInfo">
      <div>
        <div class="textAdvertisement">
          <span>文字广告:</span>
          <p>{{details.benefits}}</p>
        </div>
        <div class="contentBtn">
          <van-button :class="[btnIndex==0?'oneactive':'','Btn']" color="#e60012" type="primary" size="small" @click="btnIndex=0">合法批文</van-button>
          <van-button :class="[btnIndex==1?'twoactive':'','Btn']" color="#fe4e03" type="primary" size="small" @click="btnIndex=1">图文详情</van-button>
          <van-button :class="[btnIndex==2?'threeactive':'','Btn']" color="#000" type="primary" size="small" @click="btnIndex=2">详细参数</van-button>
          <van-button :class="[btnIndex==3?'fouractive':'','Btn']" color="#0059c9" type="primary" size="small" @click="btnIndex=3">服务保障</van-button>
        </div>
        <div class="content" v-if="btnIndex === 0">
          <div v-html="legalApproval"></div>
        </div>
        <div class="content" v-if="btnIndex === 1">
          <div v-html="graphicDetails"></div>
        </div>
        <div class="content" v-if="btnIndex === 2">
          <!-- <img style="height:100%" src="../../assets/image/miscellaneous/details.jpg" /> -->
          <div>{{details.parameter}}</div>
        </div>
        <div class="content" v-if="btnIndex === 3">
          <div>{{details.guarantee}}</div>
          <!-- <img style="height:100%" src="../../assets/image/miscellaneous/protection.jpg" /> -->
        </div>
        <div class="purchaseBtn">
          <div class="explain">
            <p>促销说明:</p>
            <p>服务承诺:</p>
          </div>
          <div class="bottomBtn">
            <div class="topListBtn" v-if="purchaseBtnList">
              <ul class="purchase" style="display:block">
                <li v-for="item in details.mallProductAssetList" :key="item.id">
                  <van-button class="listBtn" type="default" block @click="purchaseBtnList=false,buy(item)">{{item.name}}</van-button>
                </li>
              </ul>
            </div>
            <span class="iconfont icon-aliwangwang rightAliIcon"></span>
            <van-button @click="purchaseBtnList=!purchaseBtnList" class="buyLeftBtn" style color="linear-gradient(to right, #fd4d03,#fc7300)" type="primary" size="small">我要购买</van-button>
            <van-button class="buyCenterBtn" color="#fe4e03" type="primary" size="small">购物车</van-button>
            <van-button class="buyRightBtn" color="linear-gradient(to right, #fc7300 , #fd4d03)" type="primary" size="small" @click="share()">分享赚钱</van-button>
          </div>
        </div>
      </div>
      <van-popup class="showPopup" :style="{height:purchaseType==0?'65%':'60%'}" v-model="show" round position="bottom" v-if="currentlyCoupon">
        <i class="iconfont icon-guanbi closeIcon" @click="show=false"></i>
        <van-card class="card">
          <div class="title" slot="title">￥{{currentlyCoupon.price}}</div>
          <div class="price" slot="price">
            <span>配送至:</span>
          </div>
          <div class="desc" slot="desc">
            <span>库存{{details.stock}}件</span>
          </div>
          <div class="thumb" slot="thumb">
            <img :src="details.mainImage" alt />
          </div>
        </van-card>
        <div class="region" v-if="currentAddr">
          <span>配送区域</span>
          <div class="card">
            <i class="iconfont icon-tubiaozhizuomoban-" style="padding:0 10px"></i>
            <div class="whitecard">
              <span class="name">
                {{currentAddr.receiverName}}
                <span>{{currentAddr.phone}}</span>
              </span>
              <p>{{currentAddr.addrName}}</p>
              <span class="remark">
                备注:
                <input type="text" placeholder="如有特殊要求请填写" />
              </span>
            </div>
            <div style="margin:0 10px" @click="AddrPage()">
              <span style="font-size:18px" class="iconfont icon-bianji"></span>
            </div>
          </div>
          <!-- <p style="text-align: center;color:#FE4E03;font-size:14px">
            <span style="color: #666;">共{{number}}件,</span>
            合计:￥{{totalPayment.payAmount}}
          </p>-->
        </div>
        <div>
          <div class="number" v-if="purchaseType==0">
            <span>购买数量</span>
            <div class="stepper">
              <van-stepper v-model="number" min="1" max="50" />
            </div>
          </div>
        </div>
        <div class="bottomBuyBtn">
          <p>
            当前商品可使用
            <span>10积分</span>店铺优惠
          </p>
          <div class="buttonDiv">
            <van-button class="buyoneBtn" color="#fe4e03" style @click="conso()">购买声明和承诺</van-button>
            <van-button @click="payMethod=true,calculatePrice()" class="buyTwoBtn" color="#fe4e03">同意声明和购买</van-button>
          </div>
        </div>
      </van-popup>
      <van-popup v-model="payMethod" class="payMethod" round position="bottom" v-if="totalPayment">
        <div>
          <div class="title">
            <span class="iconfont icon-guanbi1 colse" @click="payMethod=false"></span>
            <span>选择支付方式</span>
            <span class="iconfont icon-wenti rightIcon"></span>
          </div>
          <div class="amount">
            <span>
              <span>￥</span>
              {{totalPayment.payAmount}}
            </span>
          </div>
          <div>
            <van-radio-group class="radio_group" v-model="radio">
              <van-cell-group class="cell_group">
                <van-cell v-for="(item,key) in payList" :key="key" class="cell" :border="false" :title="item.name" clickable @click="radio = JSON.stringify(item.id)">
                  <img slot="icon" :src="item.icon" :style="{width:'26px',height:'26px',padding:'0 10px',opacity:item.icon?'1':'0'}" />
                  <van-radio slot="right-icon" :name="JSON.stringify(item.id)" />
                </van-cell>
                <!-- <van-cell class="cell" :border="false" title="在线支付" clickable @click="radio = '2'">
                  <van-radio slot="right-icon" name="2" />
                </van-cell>
                <van-cell class="cell" :border="false" title="线下支付" clickable @click="radio = '3'">
                  <van-radio slot="right-icon" name="3" />
                </van-cell>-->
              </van-cell-group>
            </van-radio-group>
            <div class="bottomBtn">
              <van-button block color="rgb(28,145,225)" @click="payment()">立即付款</van-button>
            </div>
          </div>
        </div>
      </van-popup>
      <van-popup v-model="shows" class="showSty" round position="bottom">
        <div>
          <div class="title">
            <span class="iconfont icon-guanbi1 leftClose" @click="shows=false"></span>
            <span>订单号:2020010930122354</span>
            <span class="iconfont icon-wenti rightIcon"></span>
          </div>
          <div class="tips">
            <p>
              重要提示：选择线下支付方式请您支付成功，切勿忘记把自己的刚刚账号填写
              <input type="text" placeholder="支付卡/微信或支付宝号" />然后点击
              <span>提交</span>
            </p>
          </div>
          <div class="payCode" v-if="offlinePayments">
            <div>
              <img :src="offlinePayments.alipay" alt />
              <p>支付宝二维码</p>
            </div>
            <div>
              <img :src="offlinePayments.wechat" alt />
              <p>微信收款码</p>
            </div>
            <div>
              <img :src="offlinePayments.bank" alt />
              <p>第三方收款码</p>
            </div>
          </div>
          <div class="payBotton">
            <div>
              <router-link class="link" to="/cardPayment">
                <img src="../../assets/image/pay/银行账号.png" alt />
                <p>银行账号</p>
              </router-link>
            </div>
            <div>
              <router-link class="link" to="/pay">
                <img src="../../assets/image/pay/钱包.png" alt />
                <p>钱包</p>
              </router-link>
            </div>
          </div>
          <van-divider style="margin:5px"></van-divider>
          <div>
            <p style="text-align:center;margin:0;padding:0">上传支付凭证信息</p>
            <div>
              <van-cell-group>
                <van-field style="background:rgb(248,248,248)" v-model="username" clearable label="付款人姓名" placeholder />

                <van-field style="background:rgb(248,248,248)" v-model="accountNumber" label="付款账号" placeholder />
                <div style="background:rgb(248,248,248);display:flex;height:40px;align-items: center">
                  <span style="font-size:14px;color:#323233;padding:0 15px">上传支付凭证</span>
                  <img style="width:100px;height:38px;" :src="uploadImage" alt />
                  <van-uploader v-if="!uploadImage" :before-read="beforeRead" result-type="file" :after-read="atterRead">
                    <van-button icon="photo" style="height:40px;line-height:40px" :loading="uploadLoading">上传图片</van-button>
                  </van-uploader>
                </div>
              </van-cell-group>
              <div style="width:100%;text-align:center;padding:10px 0">
                <van-button style="width:60%;height:35px;line-height:35px;" type="primary" @click="offlinePaymentOrder()" :disabled="uploadPayInfoDisb">提交</van-button>
              </div>
            </div>
            <p style="margin:0;padding:0;color:red;font-size:12px;text-align:center">*系统检测到以上信息不完整不能退出此页</p>
          </div>
        </div>
      </van-popup>

      <van-popup v-model="rechargeMode" class="rechargeModeSty" round position="bottom">
        <div>
          <div class="title">
            <span class="iconfont icon-guanbi1 leftClose" @click="rechargeMode=false"></span>
            <span>选择支付方式</span>
            <span class="iconfont icon-wenti rightIcon"></span>
          </div>
          <div class="amount">
            <span>
              <span>￥</span>500.00
            </span>
          </div>
          <div>
            <van-radio-group class="radio_group" v-model="radio">
              <van-cell-group class="cell_group">
                <van-cell v-for="(method,i) in paymentMethod" :key="i" style="padding:6px 0;" class="cell" :border="false" :title="method.name" clickable @click="radio = i">
                  <span slot="icon">
                    <img v-if="method.icon" style="width:25px;height:25px;padding:0 5px" :src="method.icon" alt />
                  </span>
                  <van-radio slot="right-icon" :name="i" />
                </van-cell>
                <!-- <van-cell class="cell" :border="false" title="微信" clickable @click="radio = '2'">
                  <span slot="icon" class="iconfont icon-weixin"></span>
                  <van-radio slot="right-icon" name="2" />
                </van-cell>
                <van-cell class="cell" :border="false" title="云闪付" clickable @click="radio = '3'">
                  <span slot="icon" class="iconfont icon-weibiaoti--"></span>
                  <van-radio slot="right-icon" name="3" />
                </van-cell>
                <van-cell class="cell" :border="false" title="在线收款码" clickable @click="radio = '4'">
                  <van-radio slot="right-icon" name="4" />
                </van-cell>-->
              </van-cell-group>
            </van-radio-group>
            <div class="btmBtn">
              <van-button class="button" color="rgb(28,145,225)">充值完成</van-button>
            </div>
          </div>
        </div>
      </van-popup>

      <van-popup v-model="payPopup" position="bottom" style=" height: 50%; ">
        <van-password-input :value="payPassword" info="密码为 6 位数字" :focused="showKeyboard" @focus="showKeyboard = true" />
        <van-number-keyboard :show="showKeyboard" @input="onInput" @delete="onDelete" @blur="showKeyboard = false" />
        <!-- <van-button
        block
        color="#4caf50"
        style="position:absolute;bottom:0;border-radius:30px;"
        @click="deleteBank()"
      >确定</van-button>-->
      </van-popup>
    </div>
  </div>
</template>
<script>
// import wx from "weixin-js-sdk";
export default {
  data: () => ({
    areaChangeIndex: null, //配送区域change后对应改变的列表
    payPopup: false,
    showKeyboard: false,
    payPassword: "",
    graphicDetails:"",//图文详情
    legalApproval:"",//合法批文
    offlinePayments: null, //线下支付二维码
    details: {
      //商品信息
      // retailPrice: "50", //零售价
      // productName: "商品名称", //商品名称
      // benefits: "AAS；大概了解了解欧委会格式的化工科技" //文字广告
    },
    username: "", //上传支付凭证信息用户名
    accountNumber: null, //付款账号
    btnIndex: 0, //切换按钮后更换动态css的底部三角
    purchaseBtnList: false, //支付卡券li显示
    rechargeMode: false, //点击支付宝图标充值(选择支付方式)
    show: false, //选择卡券后弹出的商品数量和配送地区dialog
    // balance: false, //选择余额支付弹出的订单dialog
    shows: false, //点击线下支付弹出的dialog
    payMethod: false, //选择支付方式
    radio: "1",
    number: 0, //购买数量
    totalPayment: null, //商品支付总额
    paymentMethod: [], //支付方式
    currentlyCoupon: null, //当前选择的卡券和价格
    currentAddr: null, //当前默认地址,
    purchaseType: null, //购买类型(金银钻)
    payList: [], //支付方式列表
    uploadImage: "", //上传的凭证图片
    uploadLoading: false,
    uploadPayInfoDisb: true,
    //商品详情信息(图片+详情参数)
    condensation: {
      image: []
    }
  }),
  computed: {
    userInfo() {
      return JSON.parse(this.$store.state.memberInfo);
    },
    token() {
      return JSON.parse(this.$store.state.userInfo);
    },
    wxJsdk() {
      return this.$store.state.wxSdk;
    }
  },
  created() {
    console.log("----------------" + this.wxJsdk + "----------------");
  },
  mounted() {
    this.$axios
      .notLoggedIn(`ym/mall-product/detail?id=${this.$route.query.id}`)
      .then(msg => {
        window.console.log(msg);
        this.details = msg;
        this.condensation.image = msg.slideshow;
        this.graphicDetails = msg.productsDetail
        this.legalApproval = msg.approval
      });
  },
  watch: {
    payPassword(newValue) {
      if (newValue.length == 6) {
        this.alipayment();
        this.payPopup = false;
        this.payPassword = "";
        this.showKeyboard = false;
      }
    }
  },
  methods: {
    beforeRead(file) {
      if (file.type !== "image/jpeg") {
        this.$Toast("请上传 jpg 格式图片");
        return false;
      }
      return true;
    },
    conso() {
      //console.log(this.currentlyCoupon);
    },
    calculatePrice() {
      this.$axios
        .get(
          `ym/mall-order/cal-price?quantity=${
            this.number ? this.number : this.currentlyCoupon.quantity
          }&productId=${this.$route.query.id}`
        )
        .then(res => {
          console.log(res);
          if (res.code === 0) {
            this.totalPayment = res.data;
          }
          //console.log(res);
        });
      this.$axios.get(`ym/pay-type/list`).then(msg => {
        if (msg.code === 0) {
          this.payList = msg.data;
        }
        //console.log(msg);
      });
    },
    //我要购买点击判断卡券
    buy(index) {
      let _this = this;
      if (this.userInfo) {
        this.currentlyCoupon = {
          id:index.id,
          price: index.quantity,
          quantity: index.amount
        }
        this.$axios.get(`ym/member-address/default-address`).then(msg => {
          //console.log("获取默认地址");
          let data = msg.data;
          if (msg.code === 0) {
            data.addrName =
              data.provinceStr +
              data.cityStr +
              data.districtStr +
              data.detailAddress;
            this.currentAddr = data;
            console.log(this.currentAddr);
          } else {
            //console.log("收货地址获取失败");
          }
        });
        this.purchaseType = index;
        this.number = 0;
        this.show = true;
      } else if (!this.userInfo && this.$route.query.code) {
        this.$router.push({
          path: "/Recommend",
          query: {
            code: _this.$route.query.code
          }
        });
      } else {
        this.$router.push("/login");
      }
      // this.cardPurchase =
    },
    atterRead(e) {
      this.uploadLoading = true;
      let param = new FormData();
      param.append("files", e.file);
      let config = {
        headers: {
          Authorization:
            "bearer" + JSON.parse(this.$store.state.userInfo).access_token,
          "Content-Type": "form-data"
        }
      };
      //console.log(param.get("file")); //FormData私有类对象，访问不到，可以通过get判断值是否传进去
      this.$axios
        .post(`ym/oss-attachment/upload-image`, param, config)
        .then(msg => {
          if (msg.data.code === 0) {
            this.uploadImage = msg.data.data[0].imgSrc;
            this.uploadLoading = false;
            this.uploadPayInfoDisb = false;
            console.log(this.uploadImage);
          }
        });
      //console.log(this.uploadPayInfoDisb);
    },
    //支付宝支付
    alipayment() {
      let payInfo = {
        payType: this.radio,
        addressId: this.currentAddr.id,
        productId: this.$route.query.id,
        quantity: this.number ? this.number : this.currentlyCoupon.quantity,
        offlinePayProof: "",
        payAccount: "",
        realName: "",
        packageId: this.purchaseType.id,
        tradeType: "H5",
        paypassword: this.payPassword
      };
      // let payInfo = {
      //   productId: this.$route.query.id, //商品id
      //   payType: this.radio, //支付方式
      //   type: this.purchaseType, //购买类型
      //   quantity: this.number ? this.number : this.currentlyCoupon.quantity, //商品数量
      //   offlinePayProof: "", //线下支付凭证
      //   payAccount: "", //线下支付账号
      //   realName: "", //线下支付姓名
      //   addressId: this.currentAddr.id //地址id
      // };
      console.log(payInfo);
      this.$axios.post(`ym/mall-order/submit`, payInfo).then(msg => {
        window.console.log(msg);
        console.log(this.radio);
        if (msg.data.code === 0) {
          if (this.radio == 1) {
            const div = document.createElement("div");
            /* 此处form就是后台返回接收到的数据 */
            div.innerHTML = msg.data.data.sdkParams;
            console.log(msg.data.data.sdkParams);
            console.log(div);
            document.body.appendChild(div);
            document.forms[0].submit();
            console.log("xxx");
          } else if (this.radio == 2) {
            console.log(msg.data.data.sdkParams.mweb_url);
            window.location.href = msg.data.data.sdkParams.mweb_url;
          } else if(this.radio == 3) {
            this.$Toast('购买成功');
          }
        } else {
          this.$Toast(msg.data.msg);
        }
      });
    },
    goUpperStory() {
      this.$router.go(-1);
    },
    //获取支付方式
    getPaymentMethod() {
      this.paymentMethod = [];
      this.$axios.get(`ym/pay-type/list`).then(msg => {
        if (msg.status === 200 && msg.data.code === 0) {
          let list = msg.data.data;
          list.forEach(res => {
            this.paymentMethod.push(res);
          });
          //console.log(msg);
        }
      });
    },
    payment() {
      switch (this.radio) {
        case "1":
          this.alipayment();
          break;
        case "2":
          this.alipayment();
          break;
        case "3":
          this.payPopup = true;
          this.showKeyboard = true;
          console.log("余额支付");
          break;
        case "4":
          this.shows = true;
          this.$axios
            .get(`ym/mall-product/offline-code?id=${this.$route.query.id}`)
            .then(msg => {
              console.log(msg);
              if (msg.status === 200 && msg.data.code === 0) {
                this.offlinePayments = msg.data.data;
              } else {
                //console.log(msg.data.msg);
                // //console.log('获取支付二维码失败')
              }
              //console.log("现下支付");
            });
          break;
      }
    },
    offlinePaymentOrder() {
      let payInfo = {
        productId: this.$route.query.id, //商品id
        payType: this.radio, //支付方式
        type: this.purchaseType, //购买类型
        quantity: this.number ? this.number : this.currentlyCoupon.quantity, //商品数量
        offlinePayProof: this.uploadImage, //线下支付凭证
        payAccount: this.accountNumber, //线下支付账号
        realName: this.username, //线下支付姓名
        addressId: this.currentAddr.id //地址id
      };
      //console.log(payInfo);
      this.$axios.post(`ym/mall-order/submit`, payInfo).then(msg => {
        //console.log(msg.data.data.sdkParams);
        if (msg.data.code === 0) {
          this.$Notify({ type: "success", message: msg.data.msg });
        } else {
          this.$Notify({ type: "danger", message: msg.data.msg });
        }
      });
    },
    AddrPage() {
      this.$router.push("/addr");
    },
    //添加收藏
    addFavorites() {
      let data = {
        type: 1,
        targetid: this.$route.query.id
      };
      this.$axios.post(`ym/member-collect/add`, data).then(msg => {
        window.console.log(msg);
      });
    },
    share() {
      console.log(this.details)
      console.log(this.$store.state.NativeShare);
      try {
        this.$store.state.nativeShare.setShareData({
          icon:this.details.mainImage,
          link:`http://www.ym718.com/#/commodityDetails?id=${this.details.id}&code=${this.userInfo.referralCode}`,
          title: this.details.productName,
          desc: this.details.intro,
          from: "@fa-ge"
        });
        this.$store.state.NativeShare.call("wechatFriend");
      } catch (err) {
        // 如果不支持，你可以在这里做降级处理
        alert("抱歉,您当前使用的浏览器不支持分享!");
      }
      // let _this = this;
      // this.$axios.get(`ym/public/wechat-share`).then(res => {
      //   console.log(res)
      // wx.config({
      //   debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      //   appId: res.data.appid, // 必填，公众号的唯一标识
      //   timestamp: res.data.timestamp, // 必填，生成签名的时间戳
      //   nonceStr: res.data.noncestr, // 必填，生成签名的随机串
      //   signature: res.data.signature, // 必填，签名
      //   jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"] // 必填，需要使用的JS接口列表
      // });
      // });
      // wx.ready(function() {
      //   console.log("wx : success");
      // });
      // setTimeout(() => {
      //   wx.updateAppMessageShareData({
      //     title: _this.details.productName, // 分享标题
      //     desc: _this.details.intro, // 分享描述
      //     link: `http://www.ym718.com/#/commodityDetails?id=${_this.details.id}&code=${_this.userInfo.referralCode}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      //     imgUrl: _this.details.mainImage, // 分享图标
      //     success: function() {
      //       // 设置成功
      //       _this.$Toast("点击右上角分享-朋友");
      //     }
      //   });
      //   wx.updateTimelineShareData({
      //     title: _this.details.productName, // 分享标题
      //     link: `http://www.ym718.com/#/commodityDetails?id=${_this.details.id}&code=${_this.userInfo.referralCode}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      //     imgUrl: _this.details.mainImage, // 分享图标
      //     success: function() {
      //       // 设置成功
      //       // alert("点击右上角分享-朋友圈");
      //     }
      //   });
      // }, 2000);
    },
    onInput(key) {
      this.payPassword = (this.payPassword + key).slice(0, 6);
    },
    onDelete() {
      this.payPassword = this.payPassword.slice(0, this.payPassword.length - 1);
    }
  }
};
</script>
<style lang="scss" >
@import "../../assets/css/commodity.scss";

::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  text-align: left;
  padding-left: 10px;
  color: red;
  font-size: 11px;
}

::-moz-placeholder {
  /* Firefox 19+ */
  text-align: left;
  padding-left: 10px;
  color: red;
  font-size: 11px;
}

:-ms-input-placeholder {
  /* IE 10+ */
  text-align: left;
  padding-left: 10px;
  color: red;
  font-size: 11px;
}

:-moz-placeholder {
  /* Firefox 18- */
  text-align: left;
  padding-left: 10px;
  color: red;
  font-size: 11px;
}
</style>